/* 
 * 创建日期 2011-3-30
 *
 * 成都天和软件公司
 * 电话：028-85425861 
 * 传真：028-85425861-8008 
 * 邮编：610041 
 * 地址：成都市武侯区航空路6号丰德万瑞中心B座1001 
 * 版权所有
 */
package  org.fantasy.cpp.core.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import  org.fantasy.cpp.core.pojo.QueryConfig;
import  org.fantasy.cpp.core.pojo.QueryType;
import  org.fantasy.cpp.core.service.PageService;
import  org.fantasy.cpp.core.service.QueryService;
import  org.fantasy.common.db.bean.Row;
import  org.fantasy.common.util.RequestUtil;
import  org.fantasy.common.util.WebUtil;

/**
 * 查询工具
 * 
 * @author 王文成
 * @version 1.0
 * @since 2011-3-30
 */
public class QueryUtil {
	/**
	 * 取得公共查询参数
	 * 
	 * @return
	 * @throws Exception
	 */
	public static Map<String, Object> getQueryMap(HttpServletRequest request) throws Exception {
		Map<String, Object> qryMap = RequestUtil.getRequestMap(request);
		return qryMap;
	}

	/**
	 * 取得查询结果
	 * 
	 * @param request
	 * @param queryId
	 * @return
	 * @throws Exception
	 */
	public static List<Row> getList(HttpServletRequest request, Long queryId) throws Exception {
		return getList(request, queryId, getQueryMap(request));
	}

	/**
	 * 取得查询结果
	 * 
	 * @param request
	 * @param queryId
	 * @return
	 * @throws Exception
	 */
	public static List<Row> getList(HttpServletRequest request, Long queryId, Map<String, Object> qryMap) throws Exception {
		PageService pageService = (PageService) WebUtil.getBean(request, "pageService");
		QueryService queryService = (QueryService) WebUtil.getBean(request, "queryService");
		QueryConfig config = pageService.getQueryConfig(queryId);
		return getList(queryService, config, qryMap);
	}

	/**
	 * 取得查询结果
	 * 
	 * @param request
	 * @param queryId
	 * @return
	 * @throws Exception
	 */
	public static List<Row> getList(QueryService queryService, QueryConfig config, Map<String, Object> qryMap) throws Exception {
		Long type = config.getQueryTypeId();
		if (QueryType.isJavaType(type) || QueryType.isXSqlType(type) || QueryType.isSqlType(type)) {
			return queryService.qryList(config, qryMap);
		} else if (QueryType.isJSONType(type)) {
			return ParseUtil.json2List(config.getQueryConfig());
		}
		return new ArrayList<Row>(0);
	}
}
